<template>
  <div class="card" id="flight-change-order-new" tabindex="-1" role="dialog">
    <div class="card-header">
      <h5 class="text-primary">新建改签单</h5>
    </div>

    <table class="table table-sm table-striped mb-0">
      <thead>
        <tr>
          <th>票号</th>
          <th>姓名</th>
          <th class="d-none d-sm-table-cell">证件号</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(psg, index) of psgList" :key="index">
          <td>
            {{ psg.ticketNo }}
          </td>
          <td>{{ psg.name }}</td>
          <td class="d-none d-sm-table-cell">{{ psg.idNo }}</td>
          <td>
            <label for="label" @change="clickPsgCheckBox($event.target)">
              <input type="checkbox" v-model="psg.selected" />
            </label>
          </td>
        </tr>
      </tbody>
    </table>
    <table class="table table-sm table-striped mb-0">
      <thead>
        <tr class="">
          <th class="text-center">销售价</th>
          <th class="text-center">税</th>
          <th class="text-center">成本</th>
          <th class="text-center">实收</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="text-center">{{ parvalue }}</td>
          <td class="text-center">{{ tax }}</td>
          <td class="text-center">{{ cost }}</td>
          <td class="text-center">{{ amount }}</td>
        </tr>
      </tbody>
    </table>
    <div class="card-body bg-secondary py-0 text-white">待改签航班</div>
    <table class="table table-sm table-striped mb-1">
      <thead>
        <tr>
          <th class="text-center px-0">出发</th>
          <th class="text-center px-0">到达</th>
          <th class="text-center px-0">日期</th>
          <th class="text-center px-0">航班号</th>
          <th class="text-center px-0">舱位</th>
          <th class="text-center px-0 d-none d-md-table-cell">出发时间</th>
          <th class="text-center px-0 d-none d-md-table-cell">到达时间</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(flt, index) in oldFlights" :key="index">
          <td class="text-center px-0">
            {{ flt.dport }}
            <span class="small text-primary">{{ flt.dterm }}</span>
          </td>
          <td class="text-center px-0">
            {{ flt.aport }}
            <span class="small text-primary">{{ flt.aterm }}</span>
          </td>
          <td class="text-center px-0">{{ flt.ddate }}</td>
          <td class="text-center px-0">{{ flt.flightNo }}</td>
          <td class="text-center px-0">{{ flt.subclass }}</td>
          <td class="text-center px-0 d-none d-md-table-cell">
            {{ flt.dtime }}
          </td>
          <td class="text-center px-0 d-none d-md-table-cell">
            {{ flt.atime }}
          </td>
          <td>
            <label for="label" @change="clickFlightCheckBox($event.target)">
              <input type="checkbox" v-model="flt.selected" />
            </label>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="card-body bg-primary py-0 text-white">改签后</div>
    <table class="table table-sm table-striped mb-1">
      <thead>
        <tr>
          <th class="px-0 text-center" colspan="2">出发/到达机场</th>
          <th class="px-0 text-center">出发日期</th>
          <th class="px-0 text-center">航班号</th>
          <th class="px-0 text-center">舱位</th>
          <th class="px-0 text-center" colspan="2">出发/到达时间</th>
          <th class="px-0 text-center" colspan="2">出发/到达航站楼</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <template v-for="(flt, index) in newFlights">
          <flt-tr
            v-bind:flight="flt"
            v-bind:index="index"
            v-bind:mini="true"
            v-on:remove="removeNewFlights(index)"
            :key="`flt-tr-` + index"
          ></flt-tr>
        </template>
      </tbody>
    </table>
    <div
      class="card-body bg-primary py-0 text-white"
      v-if="flightCriteria.length > 0"
    >
      改签航班查询
    </div>
    <div class="card-body">
      <form
        class="row row-cols-lg-auto g-3 align-items-center"
        v-for="(info, index) of flightCriteria"
        :key="index"
      >
        <div class="col-12">
          <div class="input-group">
            <div class="input-group-text">出发</div>
            <input
              type="text"
              class="form-control"
              :value="info.dport"
              readonly
            />
          </div>
        </div>

        <div class="col-12">
          <div class="input-group">
            <div class="input-group-text">到达</div>
            <input
              type="text"
              class="form-control"
              :value="info.aport"
              readonly
            />
          </div>
        </div>

        <div class="col-12">
          <div class="input-group">
            <div class="input-group-text">日期</div>
            <my-date-picker
              :id="`ddate_${index}`"
              v-model="info.ddate"
              placeholder="出发日期"
            ></my-date-picker>
          </div>
        </div>

        <div class="col-12">
          <button
            type="button"
            class="btn btn-primary"
            @click.stop="searchFlight($event.target, index)"
          >
            查找航班
          </button>
        </div>
      </form>
    </div>
    <template v-if="flightSearchResult.length > 0">
      <flight-search-result
        :flights="flightSearchResult"
        @confirmFlight="confirmFlight"
      ></flight-search-result>
    </template>

    <div class="card-body py-0" v-if="newFlights.length > 0">
      <div class="row mb-1">
        <label class="col-form-label col-3 text-end"> 改签类型 </label>
        <div class="col-8">
          <div class="form-check form-check-inline">
            <input
              class="form-check-input"
              type="radio"
              value="0"
              v-model.number="reasonCode"
            />
            <label class="form-check-label">升舱</label>
          </div>
          <div class="form-check form-check-inline">
            <input
              class="form-check-input"
              type="radio"
              value="1"
              v-model.number="reasonCode"
            />
            <label class="form-check-label">更改</label>
          </div>
          <div class="form-check form-check-inline">
            <input
              class="form-check-input"
              type="radio"
              value="2"
              v-model.number="reasonCode"
            />
            <label class="form-check-label">签转</label>
          </div>
        </div>
      </div>
      <div class="row mb-1">
        <label class="col-form-label col-3 text-end"> 航司收费 </label>
        <div class="col-8">
          <input
            type="text"
            class="form-control form-control-sm"
            v-model.number="airChangeFee"
          />
        </div>
      </div>
      <div class="row mb-1">
        <label class="col-form-label col-3 text-end"> 我司服务费 </label>
        <div class="col-8">
          <input
            type="text"
            class="form-control form-control-sm"
            v-model.number="serviceCharge"
          />
          <template v-if="changeFee > 0">
            <span class="text-muted small"
              >收费标准: {{ changeFee }}元/人/段</span
            >
            <button class="btn btn-sm" @click.stop="autoCalcServiceCharge()">
              自动计算
            </button>
          </template>
        </div>
      </div>
      <div class="row mb-1">
        <label class="col-form-label col-3 text-end"> 实收客户 </label>
        <div class="col-8">
          <input
            type="text"
            class="form-control form-control-sm"
            v-model.number="total"
          />
          <span class="text-muted small">实收客户金额，用于计算我司服务费</span>
        </div>
      </div>
      <div class="row mb-1">
        <label class="col-form-label col-3 text-end"> 备注 </label>
        <div class="col-8">
          <input
            type="text"
            class="form-control form-control-sm"
            v-model="remark"
          />
        </div>
      </div>
    </div>
    <div class="card-footer text-center" v-if="newFlights.length > 0">
      <button type="button" class="btn btn-primary" @click.stop="ok()">
        创建改签单
      </button>
    </div>
  </div>
</template>

<script>
import PriceInfo from "@/common/PriceInfo.js";
import {
  searchFlightOrderDetail,
  convertPriceInfo,
  queryFlightOrderChange,
} from "@/api/flight.js";
import {
  processPnrFlightContent,
  createChangeOrderMulti,
} from "@/api/flight-change.js";
import FltTr from "@/components/flt-tr.vue";
import { searchServiceTemplateByCustomer } from "@/api/customer.js";
import MyDatePicker from "@/components/my-datepicker.vue";
import FlightSearchResult from "./flight-search-result.vue";

export default {
  components: {
    FltTr,
    MyDatePicker,
    FlightSearchResult,
  },
  data() {
    return {
      id: 0,
      detail: null,

      changeFee: 0,
      customerId: 0,
      oldPnrNo: "",
      cost: 0,
      amount: 0,
      parvalue: 0,
      tax: 0,
      orderId: 0,
      orderNo: "",
      parentChangeOrderNo: "",
      airChangeFee: 0,
      serviceCharge: 0,
      total: 0,
      remark: "",
      reasonCode: 0,
      intlTicket: -1,
      psgList: [],

      quickInput: "",
      fltId: 0,

      oldFlights: [],
      newFlights: [],

      flightCriteria: [],

      flightSearchResult: [],

      onlyOneTicketAllowed: false,
    };
  },
  watch: {
    quickInput: function (newVal, oldVal) {
      this.processQuickInput();
    },
    serviceCharge: function () {
      this.calc();
    },
    airChangeFee: function () {
      this.calc();
    },
    total: function () {
      this.calc2();
    },
    customerId: function () {
      this.getChangeFee();
    },
  },
  mounted: function () {
    this.id = parseInt(this.$route.query.id);
    this.searchOrderDetail();
  },
  methods: {
    showErrMsg: function (msg, msgType) {
      this.$store.dispatch("showAlertMsg", {
        errMsg: msg,
        errMsgType: msgType,
      });
    },
    searchOrderDetail: function () {
      searchFlightOrderDetail(this.id, (v) => {
        this.detail = v;
        this.prepareData();
      });
    },

    prepareData: function () {
      this.psgList.splice(0);
      for (const info of this.detail.passengers) {
        this.psgList.push({
          ticketNo: info.ticketNo,
          name: info.name,
          idNo: info.idNo,
          selected: false,
        });
      }

      this.oldFlights.splice(0);
      this.newFlights.splice(0);
      for (const flt of this.detail.flights) {
        this.oldFlights.push({
          dport: flt.dport,
          dportName: flt.dportName,
          dterm: flt.dterm,
          aport: flt.aport,
          aportName: flt.aportName,
          aterm: flt.aterm,
          ddate: flt.ddate,
          flightNo: flt.flightNo,
          dtime: flt.dtime,
          atime: flt.atime,
          subclass: flt.subclass,
          selected: true,
          fltType: 0,
          fltId: this.newId(),
        });
      }

      const psgType = this.detail.passengers[0].psgType;
      let psgPrice = new PriceInfo();
      convertPriceInfo(this.detail.prices, psgType, psgPrice);
      console.log(psgPrice);

      this.amount = psgPrice.amount;
      this.cost = psgPrice.cost;
      this.parvalue = psgPrice.parValue;
      this.tax = psgPrice.tax;

      this.orderNo = this.detail.orderNo;
      this.orderId = this.detail.id;
      this.intlTicket = this.detail.intlTicket;

      this.adjustFlightCriteria();
    },
    newId: function () {
      this.fltId = this.fltId + 1;
      return this.fltId;
    },
    ok: function () {
      // 检查是否选择了签转的票号
      let psgCount = 0;
      for (const psg of this.psgList) {
        if (psg.selected) {
          psgCount++;
        }
      }

      if (psgCount === 0) {
        this.showErrMsg("请选择需要签转的票号", "danger");
        return;
      }

      if (psgCount > 1 && this.onlyOneTicketAllowed) {
        this.showErrMsg("只允许选择一个票号进行操作", "danger");
        return;
      }

      const changeFlights = [];
      let count = 0;
      let newCount = 0;
      //原有航班
      for (const flt of this.oldFlights) {
        if (flt.selected === false) continue;

        if (flt.fltType === 0) {
          count++;
        } else {
          newCount++;
        }

        changeFlights.push(flt);
      }

      //新航班
      for (const flt of this.newFlights) {
        if (flt.selected === false) continue;

        if (flt.fltType === 0) {
          count++;
        } else {
          newCount++;
        }

        changeFlights.push(flt);
      }

      if (count === 0 || newCount === 0) {
        this.showErrMsg("请填写签转内容", "danger");
        return;
      }

      this.doCreateChangeOrder({
        tickets: this.psgList,
        parvalue: this.parvalue,
        tax: this.tax,
        amount: this.amount,
        cost: this.cost,
        airChangeFee: this.airChangeFee,
        serviceCharge: this.serviceCharge,
        orderId: this.orderId,
        orderNo: this.orderNo,
        parentChangeOrderNo: this.parentChangeOrderNo,
        reasonCode: this.reasonCode,
        reasonDesc: this.reasonDesc,
        remark: this.remark,
        intlTicket: this.intlTicket,
        oldPnrNo: this.oldPnrNo,
        flights: changeFlights,
      });
    },
    doCreateChangeOrder: function (info) {
      createChangeOrderMulti(JSON.stringify(info), (jsonResult) => {
        if (jsonResult.status !== "OK") {
          this.showErrMsg(jsonResult.errmsg, "danger");
        } else {
          this.showErrMsg("操作成功");
          this.$router.push("/flt/change/order/" + jsonResult.returnCode);
        }
      });
    },
    reset: function () {
      this.airChangeFee = 0;
      this.serviceCharge = 0;
      this.remark = "";
      this.reasonDesc = "";
    },
    processQuickInput: function () {
      if (this.quickInput.length < 6) {
        return;
      }
      const idx = this.quickInput.indexOf(".");
      // console.log(idx)
      if (idx > 0) {
        processPnrFlightContent({ content: this.quickInput }, (v) => {
          if (v !== null && v.flight !== null) {
            // console.log(v)
            this.quickInput = "";
            this.newFlights.push({
              dport: v.flight.dport,
              dportName: v.flight.dportName,
              dterm: v.flight.dterm,
              aport: v.flight.aport,
              aportName: v.flight.aportName,
              aterm: v.flight.aterm,
              ddate: v.flight.ddate,
              flightNo: v.flight.flightNo,
              dtime: v.flight.dtime,
              atime: v.flight.atime,
              subclass: v.flight.subclass,
              selected: true,
              fltType: 1,
              fltId: this.newId(),
            });
          }
        });
      }
    },
    addNew: function () {
      this.newFlights.push({
        dport: "",
        dportName: "",
        dterm: "",
        aport: "",
        aportName: "",
        aterm: "",
        ddate: "",
        flightNo: "",
        dtime: "",
        atime: "",
        subclass: "",
        selected: true,
        fltType: 1,
        fltId: this.newId(),
      });
    },
    removeNewFlights: function (index) {
      this.newFlights.splice(index, 1);
    },
    calc: function () {
      this.total = this.airChangeFee + this.serviceCharge;
    },
    calc2: function () {
      this.serviceCharge = this.total - this.airChangeFee;
    },
    getChangeFee: function () {
      searchServiceTemplateByCustomer(this.customerId, (v) => {
        console.log(v);
        if (v !== null && v.flightChangeFee !== undefined) {
          this.changeFee = v.flightChangeFee;
          this.autoCalcServiceCharge();
        }
      });
    },
    flightCount: function () {
      let count = 0;
      for (let i = 0; i < this.oldFlights.length; i++) {
        if (this.oldFlights[i].selected) {
          count = count + 1;
        }
      }
      return count;
    },
    autoCalcServiceCharge: function () {
      this.serviceCharge = this.flightCount() * this.changeFee;
      this.calc();
    },
    clickPsgCheckBox: function (btn) {
      console.log(btn);
    },
    clickFlightCheckBox: function (btn) {
      // console.log(btn);
      // console.log(this.oldFlights);
      adjustFlightCriteria();
    },
    adjustFlightCriteria: function () {
      this.flightCriteria.splice(0);
      for (const flt of this.oldFlights) {
        if (!flt.selected) {
          continue;
        }

        let selected = false;
        for (const flt1 of this.newFlights) {
          if (flt1.dport === flt.dport && flt1.aport === flt.aport) {
            selected = true;
            break;
          }
        }

        if (selected) {
          continue;
        }

        this.flightCriteria.push({
          dport: flt.dport,
          aport: flt.aport,
          ddate: flt.ddate,
        });
      }
      // console.log(this.flightCriteria);
    },
    searchFlight: function (btn, index) {
      $(btn).attr("disabled", true);
      queryFlightOrderChange(
        this.id,
        JSON.stringify(this.flightCriteria),
        (v) => {
          // console.log(v);
          if (v.errcode === 0) {
            this.flightSearchResult = v.dataList;
          } else {
            this.showErrMsg(v.errmsg, "danger");
          }
        },
        () => {
          $(btn).attr("disabled", false);
        }
      );
    },
    confirmFlight: function (
      dport,
      aport,
      ddate,
      flightNo,
      subclass,
      dtime,
      atime,
      dterm,
      aterm
    ) {
      // console.log("confirmFlight");
      this.newFlights.push({
        dport,
        aport,
        ddate,
        flightNo,
        subclass,
        dtime,
        atime,
        dterm,
        aterm,
        selected: true,
        fltType: 1,
        fltId: this.newId(),
      });

      this.flightSearchResult.splice(0);
      this.adjustFlightCriteria();
      // console.log(this.newFlights);
      // console.log(this.newFlights.length);
    },
  },
};
//517
</script>
